﻿
using Xacml.Core.Interfaces;
using Xacml.Core.Runtime;

namespace Xacml.Core.Runtime.Functions
{
  public class NofFunction : FunctionBase
  {
    public override string Id
    {
      get
      {
        return "urn:oasis:names:tc:xacml:1.0:function:n-of";
      }
    }

    public override IDataType Returns
    {
      get
      {
        return (IDataType) DataTypeDescriptor.Boolean;
      }
    }

    public override bool VarArgs
    {
      get
      {
        return true;
      }
    }

    public override IDataType[] Arguments
    {
      get
      {
        return new IDataType[2]
        {
          (IDataType) DataTypeDescriptor.Integer,
          (IDataType) DataTypeDescriptor.Boolean
        };
      }
    }

    public override EvaluationValue Evaluate(EvaluationContext context, params IFunctionParameter[] args)
    {
      int integerArgument = this.GetIntegerArgument(args, 0);
      if (args.Length - 1 < integerArgument)
        return EvaluationValue.Indeterminate;
      if (integerArgument == 0)
        return EvaluationValue.True;
      int num = 0;
      for (int index = 1; index < args.Length; ++index)
      {
        if (this.GetBooleanArgument(args, index))
          ++num;
        if (num == integerArgument)
          return EvaluationValue.True;
      }
      return EvaluationValue.False;
    }
  }
}
